package com.small.common.util.encrypt;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 作者: fenny
 * 邮箱: 893146555@qq.com
 * 时间: 2017/10/14 23:35
 * 描述: AES加密算法
 */
public class AES {

    /**
     * 加密key
     */
    private static final String KEY = "B6B24AEF4E6B059158B4F53F5191D9EC";

    private static final String AES = "AES";

    private static final String ALGORITHM = "SHA1PRNG";

    /**
     * 使用默认key加密
     *
     * @param content 待加密内容
     * @return 加密字符串
     * @throws Exception e
     */
    public static String encrypt(String content) throws Exception {
        return encrypt(content, KEY);
    }

    /**
     * 使用默认key解密
     *
     * @param content 已加密内容
     * @return 解密字符串
     * @throws Exception e
     */
    public static String decrypt(String content) throws Exception {
        return decrypt(content, KEY);
    }

    /**
     * 根据key加密内容
     *
     * @param content 待加密内容
     * @param key     盐
     * @return 加密字符串
     * @throws Exception e
     */
    public static String encrypt(String content, String key) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(AES);
        SecureRandom secureRandom = SecureRandom.getInstance(ALGORITHM);
        secureRandom.setSeed(key.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, AES);
        Cipher cipher = Cipher.getInstance(AES); // 创建密码器
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);// 初始化
        byte[] result = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(result); // 加密
    }

    /**
     * 根据key解密内容
     *
     * @param content 已加密内容
     * @param key     盐
     * @return 解密字符串
     * @throws Exception e
     */
    public static String decrypt(String content, String key) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(AES);
        SecureRandom secureRandom = SecureRandom.getInstance(ALGORITHM);
        secureRandom.setSeed(key.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, AES);
        Cipher cipher = Cipher.getInstance(AES); // 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, keySpec);// 初始化
        byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
        return new String(result); // 加密
    }

    public static void main(String[] args) {
        try {
           System.out.println(encrypt("2")); ;
           System.out.println(decrypt("ARdScCq/g7NX+wQzLiv/Fg=="));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
